package service.Impl;


import com.alibaba.fastjson.JSON;
import core.ParseRequestData;
import dto.StudentDto;
import mapper.Impl.StudentMapperImpl;
import mapper.StudentMapper;
import org.apache.commons.io.IOUtils;
import pojo.Page;
import pojo.Student;
import service.StudentService;
import utils.CookieUtils;
import utils.DtoUtils;
import utils.PageUtils;
import utils.ParseRequestDataUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

public class StudentServiceImpl implements StudentService {

    private StudentMapper studentMapper = new StudentMapperImpl();

    @Override
    public boolean isRegister(String username) {

        Student student = studentMapper.getStudent(username);
        return student == null;
    }

    @Override
    public boolean register(HttpServletRequest request, HttpServletResponse response) {

        ParseRequestData<Student> parseRequestData = ParseRequestDataUtils.parseRequest(request, Student.class, "upload\\student");

        Student stu = parseRequestData.getT();
        InputStream in = parseRequestData.getIn();
        OutputStream out = parseRequestData.getOut();

        boolean register = isRegister(stu.getUsername());
        if(register){
            //将数据插入到学生表中
            studentMapper.add(stu.getUsername(),stu.getPassword(),stu.getName(),stu.getSex(),stu.getAge(),stu.getHobbies(),stu.getPhoto());
            request.getSession().setAttribute("user",stu);
            request.getSession().setAttribute("role","student");
            //将头像存储到本地磁盘
            try {
                IOUtils.copy(in,out);
                in.close();
                out.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            return true;
        }else{
            try {
                in.close();
                out.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

            return false;
        }
    }

    @Override
    public String initModify(HttpServletRequest request, HttpServletResponse response) {
        if ("student".equals(request.getSession().getAttribute("role"))) {
            //从Session中获取学生对象
            Student stu = (Student) request.getSession().getAttribute("user");
            return JSON.toJSONString(stu);
        }else {
            //从数据库中获取学生对象(老师修改学生信息时使用)
            String username = request.getParameter("username");
            return JSON.toJSONString(studentMapper.getStudent(username));
        }
    }

    @Override
    public String modify(HttpServletRequest request, HttpServletResponse response) {
        ParseRequestData<Student> parseRequestData = ParseRequestDataUtils.parseRequest(request, Student.class, "upload\\student");
        Student stu = parseRequestData.getT();
        InputStream in = parseRequestData.getIn();
        OutputStream out = parseRequestData.getOut();

        String code ;

        try {
            if(stu.getPhoto() != null){//说明用户修改头像

                studentMapper.update(stu.getUsername(),stu.getName(), stu.getSex(), stu.getAge(),stu.getHobbies(),stu.getPhoto());
                IOUtils.copy(in,out);
            }else{
                studentMapper.update(stu.getUsername(),stu.getName(), stu.getSex(), stu.getAge(),stu.getHobbies());
            }
            if(in != null){
                in.close();
            }
            if(out != null){
                out.close();
            }
            code = "1"; // 更新成功
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        String role = (String) request.getSession().getAttribute("role");
        if("student".equals(role)){
            //更新Session里的数据
            request.getSession().setAttribute("name",stu.getName());
            //更新Cookie里的数据
            response.addCookie(CookieUtils.createCookie("name",stu.getName(),60*60*24*5));
            if(stu.getPhoto() != null){
                request.getSession().setAttribute("photo",stu.getPhoto());
                response.addCookie(CookieUtils.createCookie("photo",stu.getPhoto(),60*60*24*5));
            }
        }
        return code;
    }

    @Override
    public String getStudents(HttpServletRequest request, HttpServletResponse response) {
        //获取当前页数
        int curPage = Integer.parseInt(request.getParameter("curPage"));

        //设置URL
        String url = "student?action=doGetStudents&curPage=";
        //设置当前页的数据条数
        int count = 15;
        //计算偏移量
        int offset = (curPage-1)*count;
        //计算总页数
        int allCount = studentMapper.getAllCount();
        int totalPage = PageUtils.getTotalPage(allCount,count);

        //从数据库获取学生的集合
        List<Student> students = studentMapper.getStudents(offset,count);

        //处理学生集合
        List<StudentDto> studentDtos = DtoUtils.studentDtoListHandler(students);
        //封装Page对象
        Page<StudentDto> page = new Page<>(url, curPage, totalPage, studentDtos);

        //将数据存入到请求对象中
        String s = JSON.toJSONString(page);
        return s;
    }

    @Override
    public boolean delete(HttpServletRequest request, HttpServletResponse response) {
        String username = request.getParameter("username");
        studentMapper.delete(username);
        Student student = studentMapper.getStudent(username);
        if (student == null){
            return true;
        }
        return false;
    }
}
